package com.example.handheld4_gsignal_app.ui.activities;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.handheld4_gsignal_app.R;
import com.example.handheld4_gsignal_app.data.models.LocationData;
import com.example.handheld4_gsignal_app.data.models.NetworkData;
import com.example.handheld4_gsignal_app.data.models.SignalCollectionData;
import com.example.handheld4_gsignal_app.services.SignalCollectionService;
import java.util.ArrayList;
import java.util.List;

/**
 * 信号采集Activity
 */
public class SignalCollectionActivity extends AppCompatActivity implements 
        SignalCollectionService.CollectionCallback {

    private static final int PERMISSION_REQUEST_CODE = 1001;

    private TextView tvDeviceStatus;
    private TextView tvPermissionStatus;
    private TextView tvLatitude;
    private TextView tvLongitude;
    private TextView tvAltitude;
    private TextView tvAccuracy;
    private TextView tvNetworkType;
    private TextView tvOperatorName;
    private TextView tvSignalStrength;
    private TextView tvCellId;
    private Button btnRequestPermissions;
    private Button btnCollectSignal;
    private RecyclerView recyclerViewHistory;

    private SignalCollectionService signalCollectionService;
    private List<SignalCollectionData> collectionHistory;
    private boolean isCollecting = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signal_collection);

        initViews();
        initServices();
        setupClickListeners();
        checkPermissions();
    }

    private void initViews() {
        tvDeviceStatus = findViewById(R.id.tvDeviceStatus);
        tvPermissionStatus = findViewById(R.id.tvPermissionStatus);
        tvLatitude = findViewById(R.id.tvLatitude);
        tvLongitude = findViewById(R.id.tvLongitude);
        tvAltitude = findViewById(R.id.tvAltitude);
        tvAccuracy = findViewById(R.id.tvAccuracy);
        tvNetworkType = findViewById(R.id.tvNetworkType);
        tvOperatorName = findViewById(R.id.tvOperatorName);
        tvSignalStrength = findViewById(R.id.tvSignalStrength);
        tvCellId = findViewById(R.id.tvCellId);
        btnRequestPermissions = findViewById(R.id.btnRequestPermissions);
        btnCollectSignal = findViewById(R.id.btnCollectSignal);
        recyclerViewHistory = findViewById(R.id.recyclerViewHistory);

        collectionHistory = new ArrayList<>();
        recyclerViewHistory.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initServices() {
        signalCollectionService = new SignalCollectionService(this);
        updateDeviceStatus();
    }

    private void setupClickListeners() {
        btnRequestPermissions.setOnClickListener(v -> requestPermissions());
        btnCollectSignal.setOnClickListener(v -> toggleCollection());
    }

    private void checkPermissions() {
        String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE
        };

        List<String> permissionsToRequest = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }

        if (permissionsToRequest.isEmpty()) {
            updatePermissionStatus(true);
        } else {
            updatePermissionStatus(false);
        }
    }

    private void requestPermissions() {
        String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE
        };

        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            updatePermissionStatus(allGranted);
            
            if (allGranted) {
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "部分权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updatePermissionStatus(boolean granted) {
        if (granted) {
            tvPermissionStatus.setText("权限状态：已授予");
            tvPermissionStatus.setTextColor(ContextCompat.getColor(this, R.color.success));
            btnRequestPermissions.setVisibility(View.GONE);
        } else {
            tvPermissionStatus.setText("权限状态：未授予");
            tvPermissionStatus.setTextColor(ContextCompat.getColor(this, R.color.error));
            btnRequestPermissions.setVisibility(View.VISIBLE);
        }
    }

    private void updateDeviceStatus() {
        if (signalCollectionService.isLocationEnabled() && signalCollectionService.isNetworkConnected()) {
            tvDeviceStatus.setText("设备状态：就绪");
            tvDeviceStatus.setTextColor(ContextCompat.getColor(this, R.color.success));
        } else {
            tvDeviceStatus.setText("设备状态：未就绪");
            tvDeviceStatus.setTextColor(ContextCompat.getColor(this, R.color.warning));
        }
    }

    private void toggleCollection() {
        if (isCollecting) {
            stopCollection();
        } else {
            startCollection();
        }
    }

    private void startCollection() {
        signalCollectionService.startCollection(this);
        isCollecting = true;
        btnCollectSignal.setText("停止采集");
        btnCollectSignal.setBackgroundColor(ContextCompat.getColor(this, R.color.error));
        Toast.makeText(this, "开始信号采集", Toast.LENGTH_SHORT).show();
    }

    private void stopCollection() {
        signalCollectionService.stopCollection();
        isCollecting = false;
        btnCollectSignal.setText("开始采集");
        btnCollectSignal.setBackgroundColor(ContextCompat.getColor(this, R.color.primary));
        Toast.makeText(this, "停止信号采集", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCollectionSuccess(SignalCollectionData data) {
        runOnUiThread(() -> {
            collectionHistory.add(0, data); // 添加到列表开头
            // 这里可以更新RecyclerView适配器
            Toast.makeText(this, "信号采集成功", Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onCollectionError(String error) {
        runOnUiThread(() -> {
            Toast.makeText(this, "采集错误: " + error, Toast.LENGTH_LONG).show();
        });
    }

    @Override
    public void onLocationUpdate(LocationData locationData) {
        runOnUiThread(() -> {
            tvLatitude.setText(String.format("%.6f", locationData.getLatitude()));
            tvLongitude.setText(String.format("%.6f", locationData.getLongitude()));
            if (locationData.getAltitude() != null) {
                tvAltitude.setText(String.format("%.1f m", locationData.getAltitude()));
            }
            if (locationData.getAccuracy() != null) {
                tvAccuracy.setText(String.format("%.1f m", locationData.getAccuracy()));
            }
        });
    }

    @Override
    public void onNetworkUpdate(NetworkData networkData) {
        runOnUiThread(() -> {
            if (networkData.getNetworkType() != null) {
                tvOperatorName.setText(networkData.getNetworkType());
            }
            if (networkData.getOperatorName() != null) {
                tvOperatorName.setText(networkData.getOperatorName());
            }
            if (networkData.getCellId() != null) {
                tvCellId.setText(networkData.getCellId());
            }
        });
    }

    @Override
    public void onSignalStrengthUpdate(int signalStrength) {
        runOnUiThread(() -> {
            tvSignalStrength.setText(signalStrength + " dBm");
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isCollecting) {
            signalCollectionService.stopCollection();
        }
    }
}